/**
 * Created by shenj on 2016/12/29.
 */

/**
 * 智能处理照片，按照给定的宽或高
 * @param ImageBase64Data
 * @param w_h
 * @param need_base64_head
 * @param callback
 * @constructor
 */
function ImageBase64Compress(ImageBase64Data, w_h, need_base64_head, callback) {
    var p=ImageBase64Data;
    if (p) {
        var ims = new Image();
        if (p.indexOf(",") < 0) {
            p = "data:image/jpeg;base64," + p;
        }
        ims.src = p;
        ims.onload = function () {
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext('2d');
            var w = parseInt(ims.width);
            var h = parseInt(ims.height);
            var zz_w = w;
            var zz_h = h;
            console.log('原图片尺寸：' + w, h);
            if (w > w_h) {
                var cha = w - w_h;
                var now_h = h - (cha / w * h);
                zz_w = w_h;
                zz_h = now_h;
            } else if (h > w_h) {
                var ch = h - w_h;
                var now_w = w - (ch / h * w);
                zz_w = now_w;
                zz_h = w_h;
            }
            canvas.width = zz_w;
            canvas.height = zz_h;
            console.log('压缩后的图片尺寸：' + zz_w, zz_h);
            ctx.drawImage(ims, 0, 0, zz_w, zz_h);
            var base64 = canvas.toDataURL("image/jpeg");
            if (!need_base64_head) {
                base64 = base64.split(',')[1];
            }
            canvas = null;
            callback(base64)
        }
    } else {
        callback(false);
    }
}


var Base64 = {
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    encode: function (e) {
        var t = "";
        var n, r, i, s, o, u, a;
        var f = 0;
        e = Base64._utf8_encode(e);
        while (f < e.length) {
            n = e.charCodeAt(f++);
            r = e.charCodeAt(f++);
            i = e.charCodeAt(f++);
            s = n >> 2;
            o = (n & 3) << 4 | r >> 4;
            u = (r & 15) << 2 | i >> 6;
            a = i & 63;
            if (isNaN(r)) {
                u = a = 64
            } else if (isNaN(i)) {
                a = 64
            }
            t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
        }
        return t
    },
    decode: function (e) {
        var t = "";
        var n, r, i;
        var s, o, u, a;
        var f = 0;
        e = e.replace(/[^A-Za-z0-9+/=]/g, "");
        while (f < e.length) {
            s = this._keyStr.indexOf(e.charAt(f++));
            o = this._keyStr.indexOf(e.charAt(f++));
            u = this._keyStr.indexOf(e.charAt(f++));
            a = this._keyStr.indexOf(e.charAt(f++));
            n = s << 2 | o >> 4;
            r = (o & 15) << 4 | u >> 2;
            i = (u & 3) << 6 | a;
            t = t + String.fromCharCode(n);
            if (u != 64) {
                t = t + String.fromCharCode(r)
            }
            if (a != 64) {
                t = t + String.fromCharCode(i)
            }
        }
        t = Base64._utf8_decode(t);
        return t
    },
    _utf8_encode: function (e) {
        e = e.replace(/rn/g, "n");
        var t = "";
        for (var n = 0; n < e.length; n++) {
            var r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r)
            } else if (r > 127 && r < 2048) {
                t += String.fromCharCode(r >> 6 | 192);
                t += String.fromCharCode(r & 63 | 128)
            } else {
                t += String.fromCharCode(r >> 12 | 224);
                t += String.fromCharCode(r >> 6 & 63 | 128);
                t += String.fromCharCode(r & 63 | 128)
            }
        }
        return t
    },
    _utf8_decode: function (e) {
        var t = "";
        var n = 0;
        var r = c1 = c2 = 0;
        while (n < e.length) {
            r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r);
                n++
            } else if (r > 191 && r < 224) {
                c2 = e.charCodeAt(n + 1);
                t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                n += 2
            } else {
                c2 = e.charCodeAt(n + 1);
                c3 = e.charCodeAt(n + 2);
                t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                n += 3
            }
        }
        return t
    }
};


String.prototype.base64_Encode = function () {
    return jtool.Base64.encode(this);
};

String.prototype.base64_Decode = function () {
    return Base64.decode(this);
};

String.prototype.replaceAll = function (findText, replaceText) {
    var raRegExp = new RegExp(findText, "g");
    return this.replace(raRegExp, replaceText);
}

//扩展字符串方法，取右边文本
String.prototype.right = function (length_) {
    var _from = this.length - length_;
    if (_from < 0) _from = 0;
    return this.substring(this.length - length_, this.length);
}

//扩展字符串方法，取左边文本
String.prototype.left = function (length_) {
    var _from = 0;
    return this.substring(_from, length_);
}


/**
 * 简易模板引擎，使用{key} 做为占位符
 * @param context
 * @param removeEmptyKey 移除未匹配的占位符
 * @returns {*}
 */
String.prototype.render = function (context) {
    function render(template, context) {
        var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
        return template.replace(tokenReg, function (word, slash1, token, slash2) {
            if (slash1 || slash2) {
                return word.replace('\\', '');
            }
            // console.log(token);
            var variables = token.replace(/\s/g, '').split('.');
            var currentObject = context;
            var i, length, variable;
            for (i = 0, length = variables.length, variable = variables[i]; i < length; ++i) {
                currentObject = currentObject[variable];
                if (currentObject === undefined) {
                    return word;
                } else if (currentObject === null) {
                    return '';
                }
            }
            return currentObject;
        })
    }

    return render(this, context);
};

var jtool = (function ($) {
    !(function ($) {
        $.fn.cerialize = function (options) {
            return $.param(this.cerializeArray(options));
        };

        $.fn.cerializeArray = function (options) {
            var o = $.extend({}, options || {});

//            var rselectTextarea = /select|textarea/i;
//            var rinput = /text|hidden|password|search/i;

            return $.makeArray(this.find("[name]").filter("input, select, textarea").map(function (i, elem) {
                var val = $(this).val();

                if (val === null) {
                    return null;
                }

                if ($.isArray(val)) {
                    return $.map(val, function (val, i) {
                        return {name: elem.name, value: val};
                    });
                }
                else {
                    if (this.type === 'checkbox') {
                        if (!this.checked) {
                            val = null;
                        }
                    } else if (this.type === "datetime-local") {
                        val = val.replace("T", " ");
                    }
                    return {name: elem.name, value: val};
                }
            }));
        };

        $.fn.cerializeObject = function () {

            var self = this,
                json = {},
                push_counters = {},
                patterns = {
                    "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
                    "key": /[a-zA-Z0-9_]+|(?=\[\])/g,
                    "push": /^$/,
                    "fixed": /^\d+$/,
                    "named": /^[a-zA-Z0-9_]+$/
                };


            this.build = function (base, key, value) {
                base[key] = value;
                return base;
            };

            this.push_counter = function (key) {
                if (push_counters[key] === undefined) {
                    push_counters[key] = 0;
                }
                return push_counters[key]++;
            };

            this.merge = function (obj1, obj2) {
                for (var p in obj2) {
                    try {
                        // Property in destination object set; update its value.
                        if (obj2[p].constructor == Object) {
                            obj1[p] = self.merge(obj1[p], obj2[p]);
                        }
                        else {
                            if (obj1[p] === undefined) {
                                obj1[p] = obj2[p];
                            }
                            else {
                                obj1[p] = [obj1[p], obj2[p]];
                            }
                        }

                    }
                    catch (e) {
                        // Property in destination object not set; create it and set its value.
                        obj1[p] = obj2[p];
                    }
                }

                return obj1;
            };

            $.each($(this).cerializeArray(), function () {

                // skip invalid keys
                if (!patterns.validate.test(this.name)) {
                    return;
                }

                var k,
                    keys = this.name.match(patterns.key),
                    merge = this.value,
                    reverse_key = this.name;

                while ((k = keys.pop()) !== undefined) {

                    // adjust reverse_key
                    reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

                    // push
                    if (k.match(patterns.push)) {
                        merge = self.build([], self.push_counter(reverse_key), merge);
                    }

                    // fixed
                    else if (k.match(patterns.fixed)) {
                        merge = self.build([], k, merge);
                    }

                    // named
                    else if (k.match(patterns.named)) {
                        merge = self.build({}, k, merge);
                    }
                }

                json = self.merge(json, merge);
            });

            return json;
        };
    })(jQuery);


    var exp_mod = {};


    exp_mod.newGuid = (function () {
        var date = new Date();
        /* 生成GUID码 */
        var newGUID = function () {
            date = new Date();
            var guidStr = '';
            var sexadecimalDate = hexadecimal(getGUIDDate(), 8) + hexadecimal(Math.random() * 80000009 + 10000000);
            var sexadecimalTime = hexadecimal(getGUIDTime(), 16);
            for (var i = 0; i < 9; i++) {
                guidStr += Math.floor(Math.random() * 16).toString(16);
            }
            guidStr += sexadecimalDate;
            guidStr += sexadecimalTime;
            while (guidStr.length < 32) {
                guidStr += Math.floor(Math.random() * 16).toString(16);
            }
            return formatGUID(guidStr);
        };

        /*
         * 功能：获取当前日期的GUID格式，即8位数的日期：19700101
         * 返回值：返回GUID日期格式的字条串
         */
        var getGUIDDate = function () {
            return date.getFullYear() + addZero(date.getMonth() + 1) + addZero(date.getDay());
        }

        /*
         * 功能：获取当前时间的GUID格式，即8位数的时间，包括毫秒，毫秒为2位数：12300933
         * 返回值：返回GUID日期格式的字条串
         */
        var getGUIDTime = function () {
            return addZero(date.getHours()) + addZero(date.getMinutes()) + addZero(date.getSeconds()) + addZero(parseInt(date.getMilliseconds() / 10));
        }

        /*
         * 功能: 为一位数的正整数前面添加0，如果是可以转成非NaN数字的字符串也可以实现
         * 参数: 参数表示准备再前面添加0的数字或可以转换成数字的字符串
         * 返回值: 如果符合条件，返回添加0后的字条串类型，否则返回自身的字符串
         */
        var addZero = function (num) {
            if (Number(num).toString() != 'NaN' && num >= 0 && num < 10) {
                return '0' + Math.floor(num);
            } else {
                return num.toString();
            }
        }

        /*
         * 功能：将y进制的数值，转换为x进制的数值
         * 参数：第1个参数表示欲转换的数值；第2个参数表示欲转换的进制；第3个参数可选，表示当前的进制数，如不写则为10
         * 返回值：返回转换后的字符串
         */
        var hexadecimal = function (num, x, y) {
            if (y != undefined) {
                return parseInt(num.toString(), y).toString(x);
            } else {
                return parseInt(num.toString()).toString(x);
            }
        }

        /*
         * 功能：格式化32位的字符串为GUID模式的字符串
         * 参数：第1个参数表示32位的字符串
         * 返回值：标准GUID格式的字符串
         */
        var formatGUID = function (guidStr, spliteStr) {
            spliteStr = spliteStr || '';
            var str1 = guidStr.slice(0, 8) + spliteStr,
                str2 = guidStr.slice(8, 12) + spliteStr,
                str3 = guidStr.slice(12, 16) + spliteStr,
                str4 = guidStr.slice(16, 20) + spliteStr,
                str5 = guidStr.slice(20);
            return str1 + str2 + str3 + str4 + str5;
        };

        return newGUID;
    })();


    exp_mod.eventStopNext = function () {
        event.preventDefault();
        event.stopImmediatePropagation();
        event.stopPropagation();
    }

    exp_mod.copyObject = function (obj) {
        var a = JSON.stringify(obj);
        return JSON.parse(a);
    }

    /**
     * 数字动画，滚动数字
     * @param domElement 元素 $("#xx")[0] 或  getElementByid("xxx")
     * @param targetNumber 目标数字，支持小数
     */
    exp_mod.numberAnimate = function (domElement, targetNumber) {
        function leijia(aa, mubiao) {
            if (aa.innerText === (mubiao + "")) {
                return;
            }
            //console.log(".")
            if (aa.innerText.trim().length == 0) {
                aa.innerText = "0";
            }

            var a = parseInt(aa.innerText);
            if (isNaN(a)) {
                a = 0;
            }
            if (Math.abs(a - mubiao) < 5) {
                aa.innerText = mubiao;
                return;
            }
            aa.innerText = parseInt(a + (mubiao - a) / 5);
            setTimeout(function () {
                leijia(aa, mubiao);
            }, 40)
        }

        leijia(domElement, targetNumber)
    }

    exp_mod.getTimeStamp = function () {
        //获取当前时间，毫秒，做为图片名称，支持循环
        var timestamp = new Date();
        timestamp = timestamp.format("yyyyMMddHHmmssS");
        window.getTimeStamp_millTimes = window.getTimeStamp_millTimes || 0;
        window.getTimeStamp_oldmill = window.getTimeStamp_oldmill || 0;
        timestamp = timestamp * 1000;
        if (timestamp <= window.getTimeStamp_oldmill) {
            window.getTimeStamp_millTimes++;
            timestamp += window.getTimeStamp_millTimes;
        } else {
            window.getTimeStamp_millTimes = 0;
        }
        window.getTimeStamp_oldmill = timestamp;
        return timestamp;
    }

    exp_mod.setCookie = function (c_name, value, expiredays) {
        expiredays = expiredays || 1;
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = c_name + "=" + encodeURIComponent(value) +
            ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/"
    }

    exp_mod.getCookie = function (c_name) {
        if (document.cookie.length > 0) {
            var c_start = document.cookie.indexOf(c_name + "=")
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1
                var c_end = document.cookie.indexOf(";", c_start)
                if (c_end == -1) c_end = document.cookie.length
                return decodeURIComponent(document.cookie.substring(c_start, c_end))
            }
        }
        return ""
    }

    exp_mod.showOpenDialog = function (callBack) {
        var openDialog = document.getElementById("openDialog");
        if (!openDialog) {
            var saveD = "<div style='display: none'><input type='file' id='openDialog'/></div>";
            $("body").append(saveD);
            openDialog = document.getElementById("openDialog");
        }
        $(openDialog).trigger("click");
        openDialog.onchange = function () {
            if (openDialog.files) {
                callBack(openDialog.files[0]);
            } else {
                callBack(false);
            }
            openDialog.onchange = null;
            openDialog.value = '';
        };
    };

    exp_mod.showOpenDialogImage = function (callBack) {
        var openDialog = document.getElementById("openDialogImage");
        if (!openDialog) {
            var saveD = "<div style='display: none'><input  capture='camera' type='file' accept='image' id='openDialogImage'/></div>";
            $("body").append(saveD);
            openDialog = document.getElementById("openDialogImage");
        }
        $(openDialog).trigger("click");
        openDialog.onchange = function () {
            if (openDialog.files) {
                callBack(openDialog.files[0]);
            } else {
                callBack(false);
            }
            openDialog.onchange = null;
            openDialog.value = '';
        };
    };

    /**
     * 手机号中间4位替换为*号
     * @param sjh
     * @returns {string}
     */
    exp_mod.sjhMark = function (sjh) {
        var tel = sjh;
        var mtel = tel.substr(0, 3) + '****' + tel.substr(7);
        return mtel;
    }

    /**
     * 将 字符转成
     * @param str_json
     * @returns {null}
     */
    exp_mod.toJSON = function (str_json) {
        try {
            return JSON.parse(str_json);
        } catch (err) {
            return null;
        }
    };

    exp_mod.newOption = function (el, value, text) {
        text = text || value;
        el.options.add(new Option(text, value));
    };
    //随机排序数组
    exp_mod.randomArray = function (arr) {
        if ($.isArray(arr)) {
            var obj_arr = [];
            arr.forEach(function (item) {
                obj_arr.push(item);
            });
            obj_arr = obj_arr.sort(function () {
                if (Math.random() < 0.5) {
                    return -1;
                } else {
                    return 1;
                }
            });
            return obj_arr;
        } else {
            return false;
        }
    };

    /**
     js下载文件
     **/
    exp_mod.downFile = function (imagePathURL) {
        if ($("#_SAVEASIMAGE_TEMP_FRAME").length == 0) {
            $('<iframe style="display:none;" id="_SAVEASIMAGE_TEMP_FRAME"  name="_SAVEASIMAGE_TEMP_FRAME" width="0" height="0" src="about:blank"></iframe>').appendTo("body");
        }

        var down_iframe = $("#_SAVEASIMAGE_TEMP_FRAME")[0];
        down_iframe.src = "about:blank";
        down_iframe.src = imagePathURL;
    };

    exp_mod.downloadIamge = function (url, name) {
        var a = document.createElement('a')
        var event = new MouseEvent('click')

        a.download = name || '下载图片名称';
        a.href = url;

        a.dispatchEvent(event)
    }

    /**
     * 遍历js对象
     * @param man
     * @param callback index,item
     */
    exp_mod.eachObject = function (man, callback) {
        callback = callback || function (k, v) {
        };
        for (let i in man) {
            if (man.hasOwnProperty(i)) { //filter,只输出man的私有属性
                //console.log(i,":",man[i]);
                callback(i, man[i]);
            }
        }
    };
    exp_mod.Base64 = Base64;

    /**
     * 检测是否为手机号
     * @param phone
     * @returns {boolean}
     */
    exp_mod.checkPhoneNumber = function (phone) {
        if (!(/^1[1234567890]\d{9}$/.test(phone))) {
            return false;
        }
        return true;
    };


    //获取inputs的表单值，返回JSON
    exp_mod.inputsGet = function (containerSelecter) {
        var $select;
        if (typeof containerSelecter == "string") {
            $select = $(containerSelecter);
        } else {
            $select = containerSelecter;
        }

        var urlKv = $select.cerializeArray();
        var arr = {};
        for (var i = 0; i < urlKv.length; i++) {
            if (urlKv[i].value && urlKv[i].value != "null") {
                arr[urlKv[i].name] = decodeURIComponent(urlKv[i].value);
            } else {
                arr[urlKv[i].name] = "";
            }

        }

        console.log(urlKv)
        console.log(arr)
        return arr;//kv2Json(urlKv);
    };

    //给文本框赋值
    exp_mod.inputsSet = function (containerSelecter, dataArray, eachCallback) {
        eachCallback = eachCallback || function (zj) {
        }
        var $select;
        if (typeof containerSelecter == "string") {
            $select = $(containerSelecter);
        } else {
            $select = containerSelecter;
        }
        $select.find('input,select,textarea').each(function () {
            var _this = this;
            var $_this = $(this);
            var name = $_this.attr('name');
            dataArray[name] = dataArray[name] || '';
            if (dataArray[name] == 'null') {
                dataArray[name] = "";
            }
            if (_this.type == 'datetime-local') {
                if (dataArray[name]) {
                    dataArray[name] = (dataArray[name]).replace(" ", "T");
                }
            } else if (_this.type == "checkbox") {
                $_this.prop("checked", dataArray[name] ? true : false);
                _this.checked = dataArray[name] ? true : false;
            } else {
                $_this.val(dataArray[name]);
            }

            eachCallback($_this, _this);
        });
    };

    /**文件读取*******/
    exp_mod.readFile_file = function (file, onData) {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e) {
            console.log(this);
            onData(this.result);
        };
        reader.onerror = function (e) {
            onData(null);
        }
    }

    /**文件处理*******/
    exp_mod.readFile_input = function (file_input, onData) {
        var obj = file_input;
        console.log(obj)
        if (obj.files[0] == undefined) {
            onData(null);
        }
        var file = obj.files[0];
        obj.files[0] = null;
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e) {
            onData(this.result);
        };
        reader.onerror = function (e) {
            onData(null);
        }
    }
    exp_mod.eachObject = function (man, callback) {
        callback = callback || function (k, v) {
        }
        for (var i in man) {
            if (man.hasOwnProperty(i)) { //filter,只输出man的私有属性
                //console.log(i,":",man[i]);
                callback(i, man[i]);
            }
        }
    }

    /**图片处理***/
    exp_mod.compress = function (img, width, height) {
        width = width || img.width;
        height = height || img.height;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext('2d');
        canvas.width = width;
        canvas.height = height;
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        var ndata = canvas.toDataURL("image/jpeg", 0.75);
        canvas.width = canvas.height = 0;
        return ndata;
    }

    return exp_mod;
})(jQuery);
